package me.yiyou.meihua.database

import kotlinx.coroutines.flow.Flow
import me.yiyou.meihua.data.SaveBean
import me.yiyou.meihua.data.xinghuo.XHResponse
import me.yiyou.meihua.data.xinghuo.XingHuoMessage
import me.yiyou.meihua.data.xinghuo.XingHuoTool
import me.yiyou.meihua.data.xinghuo.XingHuoWebSearch
import me.yiyou.meihua.data.xinghuo.XingHuoX1
import me.yiyou.meihua.net.ApiService
import me.yiyou.meihua.net.RetrofitClient
import java.io.IOException

class MeiHuaRepository(private val meiHuaDao: MeiHuaDao) {
    /**
     * 插入数据
     */
    suspend fun insert(saveBean: SaveBean) {
        val rowId = meiHuaDao.insert(saveBean)
        if (rowId == -1L) throw IOException("插入失败")
    }

    /**
     * 获取所有数据
     */
    val allList: Flow<List<SaveBean>> = meiHuaDao.getAll()

    private val apiService = RetrofitClient.createService(ApiService::class.java)

    /**
     * 获取ai回复,一次性回复
     */
    suspend fun getChatCompletion(
        model: String,
        userId: String,
        userMessage: String,
        stream: Boolean = false,
        max_tokens: Int = 10000,
        enableWebSearch: Boolean = true
    ): Result<XHResponse> {
        return try {
            val request = XingHuoX1(
                model = model,
                user = userId,
                messages = listOf(XingHuoMessage(role = "user", content = userMessage)),
                stream = stream,
                max_tokens = max_tokens,
                tools = if (enableWebSearch) {
                    listOf(
                        XingHuoTool(
                            type = "web_search", web_search = XingHuoWebSearch(
                                enable = true, search_mode = "deep"
                            )
                        )
                    )
                } else null
            )

            val response = apiService.chatCompletion(request)
            if (response.isSuccess()) {
                Result.success(response)
            } else {
                Result.failure(Exception(response.message))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
}